Page({
  data: {
    showRule: false,
    signList: [],
    totalCheckInDays: 0,
    startDate: null,
    endDate: null,
    value: 0,
    type: null,
    card: []
  },

  onLoad() {
    wx.cloud.init({ env: 'cloud1-8g4hfxry284035d7' }); // 确保云开发已初始化

    const db = wx.cloud.database();

    // 获取奖励规则
    db.collection('checkin_card').orderBy('days', 'asc').get().then(res => {
      this.setData({ card: res.data });

      // 获取用户签到记录
      db.collection('checkin_sign').orderBy('date', 'asc').get().then(res2 => {
        const signList = res2.data.map(item => item.date);
        this.setData({ signList, totalCheckInDays: signList.length });

        // 计算当前奖励
        const reward = this.data.card.find(c => signList.length >= c.days) || { value: 1, type: "星币" };
        this.setData({ value: reward.value, type: reward.type });
      });
    });

    db.collection('checkin_card').get().then(res => {
      console.log('签到规则数据：', res.data);
    });

    db.collection('checkin_sign').get().then(res => {
      console.log('签到数据：', res.data);
    });
    

    // 设置当前月开始和结束日期字符串
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    const pad = n => (n < 10 ? '0' + n : '' + n);

    const startStr = `${year}-${pad(month)}-01`;
    const endStr = `${year}-${pad(month)}-${pad(new Date(year, month, 0).getDate())}`;

    this.setData({ startDate: startStr, endDate: endStr });
  },

  onSign(e) {
    const date = e.detail.date;

    if (this.data.signList.includes(date)) {
      wx.showToast({ title: '今日已签到', icon: 'none' });
      return;
    }

    wx.cloud.callFunction({
      name: 'signIn',
      data: { date },
      success: res => {
        console.log('签到云函数返回：', res);
        if (res.result.success) {
          const newSignList = [...this.data.signList, date];
          const total = res.result.totalCheckInDays;

          // 重新计算奖励
          const reward = this.data.card.find(c => total >= c.days) || { value: 1, type: "星币" };

          this.setData({
            signList: newSignList,
            totalCheckInDays: total,
            value: reward.value,
            type: reward.type
          });

          wx.showToast({ title: '签到成功', icon: 'success' });
        } else {
          wx.showToast({ title: res.result.message || '签到失败', icon: 'none' });
        }
      },
      fail: err => {
        wx.showToast({ title: '签到失败', icon: 'none' });
        console.error('调用签到云函数失败:', err);
      }
    });
  },

  showRulePopup() {
    this.setData({ showRule: true });
  },

  closeRule() {
    this.setData({ showRule: false });
  },

  stopTap() {
    // 阻止点击穿透
  }
});
